package com.hslxy.niukewang.service;

import com.hslxy.niukewang.dao.elasticsearch.DiscusspostRepository;
import com.hslxy.niukewang.entity.DiscussPost;
import org.elasticsearch.index.query.QueryBuilders;

import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.*;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ElasticsearchService {
    @Autowired
    private DiscusspostRepository discusspostRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    public void saveDiscussPost(DiscussPost post){
        discusspostRepository.save(post);
    }
    public void deleteDiscussPost(int id){
        discusspostRepository.deleteById(id);
    }
    public Page searchDiscussPost(String keyword, int current, int limit){
        Query build = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.multiMatchQuery(keyword, "title", "content"))
                .withSort(SortBuilders.fieldSort("type").order(SortOrder.DESC))
                .withSort(SortBuilders.fieldSort("score").order(SortOrder.DESC))
                .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
                .withPageable(PageRequest.of(current, limit))
                .withHighlightFields(
                        new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>"),
                        new HighlightBuilder.Field("content").preTags("<em>").postTags("</em>")
                ).build();
        SearchHits<DiscussPost> hits = elasticsearchRestTemplate.search(build, DiscussPost.class);
        if (hits.getTotalHits() <= 0) {
            return null;
        }
        hits.forEach(e->{
            System.out.println(e.getContent());
            List<String> titleField = e.getHighlightFields().get("title");
            if (titleField != null) {
                e.getContent().setTitle(titleField.get(0));
            }
            List<String> contentField = e.getHighlightFields().get("content");
            if(contentField != null){
                e.getContent().setContent(contentField.get(0));
            }

        });
        SearchPage<DiscussPost> page = SearchHitSupport.searchPageFor(hits, build.getPageable());
        return (Page) SearchHitSupport.unwrapSearchHits(page);
    }
}
